import 'dart:io';
import 'dart:ui';

import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:path_provider/path_provider.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import '../../core/index.dart';

/// 编辑个人资料页面
class VamosEditProfileInterface extends StatefulWidget {
  const VamosEditProfileInterface({super.key});

  @override
  State<VamosEditProfileInterface> createState() =>
      _VamosEditProfileInterfaceState();
}

class _VamosEditProfileInterfaceState extends State<VamosEditProfileInterface> {
  late UserDataEntity _currentUser;
  String _tempDisplayName = '';
  String _tempPersonalBio = '';
  String _tempProfileImage = '';
  bool _hasChanges = false;

  @override
  void initState() {
    super.initState();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    if (_tempDisplayName.isEmpty) {
      _initializeUserData();
    }
  }

  /// 初始化用户数据
  void _initializeUserData() {
    final store = StoreProvider.of<AppState>(context);
    final currentUser = store.state.userState.activeUser;

    if (currentUser != null) {
      _currentUser = currentUser;
      _tempDisplayName = currentUser.displayName;
      _tempPersonalBio = currentUser.personalBio;
      _tempProfileImage = currentUser.profileImage;
    }
  }

  @override
  Widget build(BuildContext context) {
    return StoreConnector<AppState, AppState>(
      converter: (store) => store.state,
      builder: (context, state) {
        final currentUser = state.userState.activeUser;

        if (currentUser == null) {
          return Scaffold(
            body: Center(
              child: Text(
                'Please login to edit profile',
                style: TextStyle(color: Colors.white, fontSize: 18.sp),
              ),
            ),
          );
        }

        return Scaffold(
          body: Container(
            width: double.infinity,
            height: double.infinity,
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/my_background.png'),
                fit: BoxFit.cover,
              ),
            ),
            child: _buildEditProfileContent(currentUser),
          ).safeArea(top: false, bottom: false),
        );
      },
    );
  }

  Widget _buildEditProfileContent(UserDataEntity currentUser) {
    return Column(
      children: [
        // 顶部导航栏
        _buildTopNavigationBar(),

        // 头像编辑区域
        _buildProfileImageSection(),

        // 编辑选项区域
        Expanded(child: _buildEditOptionsSection()),

        // 保存按钮
        _buildSubmitButton(),

        SizedBox(height: 50.h),
      ],
    );
  }

  /// 构建顶部导航栏
  Widget _buildTopNavigationBar() {
    return Container(
      padding: EdgeInsets.only(
        top: MediaQuery.of(context).padding.top + 12.h,
        left: 16.w,
        right: 16.w,
        bottom: 12.h,
      ),
      child: Row(
        children: [
          // 返回按钮
          Icon(
            Icons.arrow_back,
            size: 26.w,
            color: Colors.white,
          ).center().inkWell(
            onTap: () {
              _handleBackPress();
            },
          ),

          // 标题
          Expanded(
            child: Center(
              child: Text(
                'EDIT',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w700,
                  fontFamily:
                      GoogleFonts.goblinOne(
                        fontWeight: FontWeight.w700,
                      ).fontFamily,
                ),
              ),
            ),
          ),

          SizedBox(width: 36.w),
        ],
      ),
    );
  }

  /// 构建头像编辑区域
  Widget _buildProfileImageSection() {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 30.h),
      child: Stack(
        children: [
          // 头像
          Container(
            width: 77.w,
            height: 77.w,
            margin: EdgeInsets.all(2.w),
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              color: Colors.transparent,
              border: Border.all(color: Colors.grey, width: 2),
            ),
            child: ClipOval(
              child:
                  _tempProfileImage.isNotEmpty
                      ? Image.asset(
                        _tempProfileImage,
                        width: 108.w,
                        height: 108.w,
                        fit: BoxFit.cover,
                      )
                      : Icon(
                        Icons.person,
                        size: 60.w,
                        color: Colors.white,
                      ).center(),
            ),
          ).inkWell(
            onTap: () {
              _handleImagePicker();
            },
          ),

          // 编辑图标
          Positioned(
            bottom: 0,
            right: 0,
            child: Container(
              width: 26.w,
              height: 26.w,
              decoration: BoxDecoration(
                color: Colors.white,
                shape: BoxShape.circle,
                border: Border.all(color: Colors.grey[300]!, width: 2),
              ),
              child: Icon(
                Icons.camera_alt,
                color: Colors.black,
                size: 16.w,
              ).center().inkWell(
                onTap: () {
                  _handleImagePicker();
                },
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建编辑选项区域
  Widget _buildEditOptionsSection() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      child: Column(
        children: [
          // 昵称编辑
          _buildEditOption(
            label: 'NickName',
            value: _tempDisplayName,
            isNickname: true,
            onTap: () {
              _showEditDialog(
                title: 'Edit NickName',
                initialValue: _tempDisplayName,
                onSave: (value) {
                  setState(() {
                    _tempDisplayName = value;
                    _hasChanges = true;
                  });
                },
              );
            },
          ),

          SizedBox(height: 20.h),

          // 签名编辑
          _buildEditOption(
            label: 'Signature',
            value: _tempPersonalBio,
            isNickname: false,
            onTap: () {
              _showEditDialog(
                title: 'Edit Signature',
                initialValue: _tempPersonalBio,
                onSave: (value) {
                  setState(() {
                    _tempPersonalBio = value;
                    _hasChanges = true;
                  });
                },
              );
            },
          ),
        ],
      ),
    );
  }

  /// 构建单个编辑选项
  Widget _buildEditOption({
    required String label,
    required String value,
    required bool isNickname,
    required VoidCallback onTap,
  }) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white.withOpacity(0.1),
        borderRadius: BorderRadius.circular(16.r),
        border: Border.all(color: Colors.white.withOpacity(0.2), width: 1),
      ),
      width: double.infinity,
      height: 50.h,
      child: Row(
        children: [
          // 左侧标签
          Padding(
            padding: EdgeInsets.only(left: 10.w),
            child: Text(
              label,
              style: TextStyle(
                color: Colors.white,
                fontSize: 16.sp,
                fontWeight: FontWeight.w800,
                fontFamily:
                    GoogleFonts.poppins(fontWeight: FontWeight.w800).fontFamily,
              ),
            ),
          ),

          Spacer(),

          // 中间内容
          Container(
            constraints: BoxConstraints(maxWidth: 200.w),
            child: Text(
              value.isNotEmpty ? value : 'Tap to edit',
              style: TextStyle(
                color:
                    value.isNotEmpty
                        ? Colors.white
                        : Colors.white.withOpacity(0.5),
                fontSize: 16.sp,
                fontStyle: isNickname ? FontStyle.italic : FontStyle.normal,
                fontWeight: isNickname ? FontWeight.w600 : FontWeight.w400,
                fontFamily:
                    isNickname
                        ? GoogleFonts.poppins(
                          fontWeight: FontWeight.w900,
                        ).fontFamily
                        : GoogleFonts.poppins(
                          fontWeight: FontWeight.w400,
                        ).fontFamily,
              ),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
          ),

          // 右侧箭头
          Padding(
            padding: EdgeInsets.only(right: 10.w, left: 10.w),
            child: Icon(
              Icons.arrow_forward_ios,
              color: Colors.white.withOpacity(0.7),
              size: 16.w,
            ),
          ),
        ],
      ),
    ).inkWell(onTap: onTap);
  }

  /// 构建保存按钮
  Widget _buildSubmitButton() {
    return Container(
      margin: EdgeInsets.all(16.w),
      width: double.infinity,
      height: 44.h,
      decoration: BoxDecoration(
        color: const Color(0xFFF7CEBA),
        borderRadius: BorderRadius.circular(41.r),
        boxShadow: [
          BoxShadow(
            color: Color(0xFFFB894E).withOpacity(0.3),
            blurRadius: 8.r,
            offset: Offset(0, 4.h),
          ),
        ],
      ),
      child: Text(
        'SUBMIT',
        style: TextStyle(
          color: Colors.black,
          fontSize: 18.sp,
          fontWeight: FontWeight.w700,
          fontFamily:
              GoogleFonts.protestStrike(fontWeight: FontWeight.w700).fontFamily,
        ),
      ).center().inkWell(onTap: _hasChanges ? _handleSubmit : null),
    );
  }

  /// 处理返回按钮
  void _handleBackPress() {
    if (_hasChanges) {
      _showDiscardChangesDialog();
    } else {
      Navigator.of(context).pop();
    }
  }

  /// 显示放弃更改对话框
  void _showDiscardChangesDialog() {
    showDialog(
      context: context,
      builder:
          (context) => AlertDialog(
            backgroundColor: Colors.white.withOpacity(0.9),
            title: Text(
              'Discard Changes',
              style: TextStyle(
                color: Colors.black,
                fontSize: 18.sp,
                fontWeight: FontWeight.w600,
                fontFamily:
                    GoogleFonts.poppins(fontWeight: FontWeight.w600).fontFamily,
              ),
            ),
            content: Text(
              'You have unsaved changes. Are you sure you want to discard them?',
              style: TextStyle(
                color: Colors.black,
                fontSize: 14.sp,
                fontFamily:
                    GoogleFonts.poppins(fontWeight: FontWeight.w400).fontFamily,
              ),
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(),
                child: Text(
                  'Cancel',
                  style: TextStyle(
                    color: Colors.grey[600],
                    fontSize: 14.sp,
                    fontFamily:
                        GoogleFonts.poppins(
                          fontWeight: FontWeight.w500,
                        ).fontFamily,
                  ),
                ),
              ),
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop();
                  Navigator.of(context).pop();
                },
                child: Text(
                  'Discard',
                  style: TextStyle(
                    color: Colors.red,
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w600,
                    fontFamily:
                        GoogleFonts.poppins(
                          fontWeight: FontWeight.w600,
                        ).fontFamily,
                  ),
                ),
              ),
            ],
          ),
    );
  }

  /// 处理图片选择
  void _handleImagePicker() async {
    try {
      final List<AssetEntity>? assets = await AssetPicker.pickAssets(
        context,
        pickerConfig: AssetPickerConfig(
          maxAssets: 1,
          requestType: RequestType.image,
          specialPickerType: SpecialPickerType.noPreview,
          textDelegate: const AssetPickerTextDelegate(),
        ),
      );

      if (assets != null && assets.isNotEmpty) {
        final asset = assets.first;
        final file = await asset.file;

        if (file != null) {
          // 复制图片到本地目录
          final localPath = await _copyImageToLocal(file);
          if (localPath != null) {
            setState(() {
              _tempProfileImage = localPath;
              _hasChanges = true;
            });
          }
        }
      }
    } catch (e) {
      if (mounted) {
        NotificationUtils.showError(
          context,
          message: 'Failed to select image: $e',
        );
      }
    }
  }

  /// 复制图片到本地目录
  Future<String?> _copyImageToLocal(File sourceFile) async {
    try {
      final directory = await getApplicationDocumentsDirectory();
      final profileImagesDir = Directory('${directory.path}/profile_images');

      if (!await profileImagesDir.exists()) {
        await profileImagesDir.create(recursive: true);
      }

      final fileName = 'profile_${DateTime.now().millisecondsSinceEpoch}.jpg';
      final targetFile = File('${profileImagesDir.path}/$fileName');

      await sourceFile.copy(targetFile.path);

      return '${profileImagesDir.path}/$fileName';
    } catch (e) {
      return null;
    }
  }

  /// 显示编辑对话框
  void _showEditDialog({
    required String title,
    required String initialValue,
    required Function(String) onSave,
  }) {
    final TextEditingController controller = TextEditingController(
      text: initialValue,
    );

    showDialog(
      context: context,
      builder:
          (context) => AlertDialog(
            backgroundColor: Colors.white.withOpacity(0.9),
            title: Text(
              title,
              style: TextStyle(
                color: Colors.black,
                fontSize: 18.sp,
                fontWeight: FontWeight.w600,
                fontFamily:
                    GoogleFonts.poppins(fontWeight: FontWeight.w600).fontFamily,
              ),
            ),
            content: TextField(
              controller: controller,
              style: TextStyle(
                color: Colors.black,
                fontSize: 16.sp,
                fontFamily:
                    GoogleFonts.poppins(fontWeight: FontWeight.w400).fontFamily,
              ),
              decoration: InputDecoration(
                hintText: 'Enter $title',
                hintStyle: TextStyle(color: Colors.grey[600], fontSize: 16.sp),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8.r),
                ),
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8.r),
                  borderSide: BorderSide(color: Color(0xFF83BE4A), width: 2),
                ),
              ),
              maxLines: title == 'Edit Signature' ? 3 : 1,
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(),
                child: Text(
                  'Cancel',
                  style: TextStyle(
                    color: Colors.grey[600],
                    fontSize: 14.sp,
                    fontFamily:
                        GoogleFonts.poppins(
                          fontWeight: FontWeight.w500,
                        ).fontFamily,
                  ),
                ),
              ),
              TextButton(
                onPressed: () {
                  final value = controller.text.trim();
                  if (value.isNotEmpty) {
                    onSave(value);
                    Navigator.of(context).pop();
                  }
                },
                child: Text(
                  'Save',
                  style: TextStyle(
                    color: Color(0xFF83BE4A),
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w600,
                    fontFamily:
                        GoogleFonts.poppins(
                          fontWeight: FontWeight.w600,
                        ).fontFamily,
                  ),
                ),
              ),
            ],
          ),
    );
  }

  /// 处理提交
  void _handleSubmit() async {
    try {
      final userManager = serviceLocator<ReduxUserManager>();

      final updatedUser = _currentUser.copyWith(
        displayName: _tempDisplayName,
        personalBio: _tempPersonalBio,
        profileImage: _tempProfileImage,
      );

      final success = await userManager.updateUser(updatedUser);

      if (success) {
        NotificationUtils.showSuccess(
          context,
          message: 'Profile updated successfully',
        );

        // 延迟一下让用户看到提示
        await Future.delayed(Duration(milliseconds: 500));

        if (mounted) {
          Navigator.of(context).pop();
        }
      } else {
        NotificationUtils.showError(
          context,
          message: 'Failed to update profile',
        );
      }
    } catch (e) {
      if (mounted) {
        NotificationUtils.showError(
          context,
          message: 'Error updating profile: $e',
        );
      }
    }
  }
}
